package client_agent

import (
	"encoding/json"
	"lark/proto"
	"time"

	"github.com/pkg/errors"
)

type clientInMsg struct {
	Data           []byte
	TargetService  string        `json:"service_name"`
	TargetAddr     string        `json:"target_addr"`
	ProcessTimeout time.Duration `json:"recv_timeout"`
	SourceService  string        `json:"client_service"`
}

type clientOutMsg struct {
	tag  uint16
	data []byte
}

type sessionInMsg struct {
	msgid     uint64
	retCh     chan *clientOutMsg
	data      []byte
	createdAt time.Time
}

func UnmarshalClientInMsg(payload []byte) (*clientInMsg, error) {
	var msg = new(clientInMsg)

	values := proto.SplitPayload(payload)

	if len(values) < 2 {
		return nil, errors.New("less data")

	} else if len(values) == 2 {
		msg.Data = values[0]
		msg.TargetService = string(values[1])

	} else {
		json.Unmarshal(values[2], msg)
		msg.Data = values[0]
	}

	msg.ProcessTimeout = msg.ProcessTimeout * time.Second
	return msg, nil
}
